
function showPictures(){
	var picture1 = imagePath + $('#DifferenceGamePicture1').val();
	var picture2 = imagePath + $('#DifferenceGamePicture2').val();
	
	$('#picture2').attr('src', picture2);
	$('#picture1').attr('src', picture1);
}

$(function() {
	$('#picture2').load(function(){
		DIFFERENCE_GAMES_SYSTEM_EDIT.init(differentPoints);
	});
	showPictures();
	$('#div-picture2').dblclick(function(e) {
		var x = e.pageX - $(this).position().left;
		var y = e.pageY - $(this).position().top;
		DIFFERENCE_GAMES_SYSTEM_EDIT.createMark('#div-picture2', x, y, 40, 40);
	});
	$('#DifferenceGameSystemEditForm').submit(function(){
		var diffPs = DIFFERENCE_GAMES_SYSTEM_EDIT.getMarks();
		$('#DifferenceGameDifferentPoints').val(diffPs);
	});
});

var DIFFERENCE_GAMES_SYSTEM_EDIT = {
    markCounter : 0,
    marks : {},
    init : function(marks){
    	this.marks = [];
    	for(var i=0;i<marks.length;i++){
    		this.createMark('#div-picture2', marks[i].x, marks[i].y, marks[i].w, marks[i].h);
    	}
    },
    getMarks : function(){
    	var str = '';
    	for(var id in this.marks){
    		if(this.marks[id]){
    			var $m = $('#' + id);
    			var pos = $m.position();
    			var w = $m.width();
    			var h = $m.height();
    			str += (pos.left + w / 2);
    			str += ',' + (pos.top + h / 2);
    			str += ',' + w;
    			str += ',' + h + ';' ;
    		}
    	}
    	return str;
    },
    createMark : function(id, x, y, width, height) {
		// min width
		if(!width) {
			width = 20;
		}
		if(width < 20){
			width = 20;
		}
		if(!height){
			height = 20;
		}
		if(height < 20){
			height = 20;
		}
	    this.markCounter++;
	    var markId = 'mark_' + this.markCounter;
	    $(id).append('<div id="' + markId + '" class="marker"></div>');
	    // add marks to marks list
	    this.marks[markId] = true;
	    var $mark = $('#' + markId);
	    var radius = width < height ? height : width;
	    $mark.css({
	    	borderRadius : radius + 'px',
	    	width : width + 'px',
	    	height : height + 'px',
	    	left : x - width /2 + 'px',
	    	top : y - height /2 + 'px'
	    });
	    $mark.draggable( {
		    stop : function() {
			    var left = $mark.position().left;
			    var top = $mark.position().top;
			    var width = $mark.width();
			    var height = $mark.height();
			    var cWidth = $('#div-picture2').width();
			    var cHeight = $('#div-picture2').height();
			    // remove the mark if we put it out
			    if(left > cWidth || top > cHeight || left < 0 || top < 0) {
			    	$mark.draggable('destroy').resizable('destroy').remove();
			    	DIFFERENCE_GAMES_SYSTEM_EDIT.marks[markId] = false;
			    }
		    }
	    }).resizable({
	    	minHeight : 20,
	    	minWidth : 20,
	    	handles : 'se',
	    	resize : function(){
		    	var width = $mark.width();
			    var height = $mark.height();
			    var radius = width < height ? height : width;
			    $mark.css({
			    	borderRadius : radius + 'px'
			    });
	    	}
	    });
    }
};